/**
 * 对象深拷贝
 * @param obj
 */
export const deepCopy = (obj: any): any => {
  // 检查输入是否为对象或数组
  if (typeof obj !== 'object' || obj === null) return obj;

  // 如果是函数，直接返回原函数
  if (typeof obj === 'function') return obj;

  // 根据输入的类型(对象或数组)初始化结果（添加类型断言）
  const result: Record<string, any> = Array.isArray(obj) ? [] : {};

  // 递归地拷贝每个属性或元素
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      // 添加双重类型断言确保类型安全
      result[key] = deepCopy(obj[key]);
    }
  }

  return result;
};

/**
 * @description 对象深拷贝
 * @param target 目标对象
 * @param sources 来源对象
 */
export const deepMerge = <T extends object>(target: T, ...sources: Partial<T>[]): T => {
  if (!sources.length) return target;

  const source = sources.shift();

  if (target === null || source === null) return source as T;

  if (typeof target !== 'object' || typeof source !== 'object') return target;

  // 添加类型断言
  const merged = deepCopy(target) as T;

  Object.keys(source).forEach((key) => {
    // 添加类型断言
    const targetValue = (merged as Record<string, any>)[key];

    const sourceValue = (source as Record<string, any>)[key];

    if (Array.isArray(sourceValue)) {
      (merged as Record<string, any>)[key] = deepCopy(sourceValue);
    } else if (sourceValue && typeof sourceValue === 'object') {
      (merged as Record<string, any>)[key] = deepMerge(targetValue && typeof targetValue === 'object' ? targetValue : {}, sourceValue);
    } else {
      (merged as Record<string, any>)[key] = sourceValue;
    }
  });

  return sources.length ? deepMerge(merged, ...sources) : merged;
};

/**
 *  生成uuid
 */
export const uuid = () => {
  return Date.now() + '_' + (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};

/**
 * 首字母大写
 * @param str 字符串
 */
export const capitalizeFirstLetter = (str: string): string => {
  return str.charAt(0).toUpperCase() + str.slice(1);
};

interface TreeNode {
  key: string;
  list?: TreeNode[];
  [key: string]: any;
}
/**
 * 递归查找树结构中的节点
 * @param {Array} nodes 节点数组
 * @param {string} targetKey 目标key
 * @returns 找到的节点或null
 */
export const findTreeNode = (nodes: TreeNode[], targetKey: string): TreeNode | null => {
  for (const node of nodes) {
    if (node.key === targetKey) {
      return node; // 找到目标节点
    }
    // 递归查找子节点（如果存在子节点数组）
    if (node.list && Array.isArray(node.list) && node.list.length > 0) {
      const found = findTreeNode(node.list, targetKey);
      if (found) return found;
    }
  }
  return null; // 未找到
};
